-- UIRotineShop
-- Create by cheny3 Nov/11/2016
-- 常规活动兑换界面

require "game/ui/form/activity/UIRotineShopDetail"

-- UIRotineShop继承自Layer
UIRotineShop = class("UIRotineShop", function()
    return cc.Layer:create();
end);

function UIRotineShop.create()
    return UIRotineShop.new();
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UIRotineShop:ctor()
    -- 初始化
    self:setName("UIRotineShop");
    local node = cc.CSLoader:createNode("layout/shop/BlackMarket.csb");
    self:addChild(node);
    self.node = node;

    self.id = RotineActivityM.getCurRotineActivityId();
    self.info = RotineActivityM.getUserRotineInfo();

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.node, "CT/mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.node, "CT/mask4");
    mask4:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 初始化
    self:init();

    -- 注册点击事件
    self:registerTouchEvent();

    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIRotineShop:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- mask居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "mask");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化标签页
function UIRotineShop:init()
    -- 记录滚动容器原始宽高
    -- 切换标签页时，滚动容器的内部滚动区域可能会发生变化，因此这里需要将原始宽高记录下来
    local scrollview = findChildByName(self.node, "CT/scroll_view");
    self.initInnerHeight = scrollview:getInnerContainerSize().height;
    self.initInnerWidth  = scrollview:getInnerContainerSize().width;
end

-- 初始化商品格
function UIRotineShop:initGoodsGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();

    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    if shopCount <= 6 then
        leftWGap = 41;
    end

    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    wGap = 15;

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerPetShopTouchEvent);
end

-- 清空所有的商品格
function UIRotineShop:clearAllGrid()
    -- 格子总数
    local totalGridCount = MAX_GRID_ROW * MIN_GRID_COLUMN;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 重绘
function UIRotineShop:redraw()
    -- 去除所有
    self.scrollView:removeAllChildren();
    local soldOutTipsLabel = findChildByName(self.node, "CT/sold_out_tips");
    local slimeImage = findChildByName(self.CT, "slime");
    soldOutTipsLabel:setVisible(false);
    slimeImage:setVisible(false);

    -- 刷新按钮
    local btnRefresh = findChildByName(self.node, "BT/refresh");
    btnRefresh:setVisible(false);

    -- 初始化格子
    self:initGoodsGrids(self.node);
    -- 绘制详细内部界面
    self:redrawNext();
end

-- 重绘宝罐页面
function UIRotineShop:redrawNext()
    -- 主标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);

    local rotineType = RotineActivityM.getRotineInfo()["rotine_type"];
    local name = getLocStr("rotine_title_" .. rotineType);
    titleLabel:setString(name);

    -- 副标题
    self:redrawTime();

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();

    local totalGoodsCount = #goodsList;

    if not goodsList or #goodsList == 0 then
        cclog("收集商品信息失败。");
        self:clearAllGrid();
        return;
    end

    -- 显示商品信息
    local totalGoodsCount = #goodsList;

    -- 绘制商品信息
    self:redrawGoods(goodsList);
end

-- 对应的奖励图标
function UIRotineShop:getBonusIcon(bonus)
    local iconPath;
    if bonus[1] == 1 then
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
    elseif bonus[1] == 2 then
        iconPath = getLevelItemIconPath(FieldsM.query(bonus[2], "icon"));
    end

    return iconPath;
end

-- 显示商品信息
function UIRotineShop:redrawGoods(goodsList)
    -- 显示商品信息
    local totalGoodsCount = #goodsList;
    for i = 1, totalGoodsCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel  = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel    = grid:getChildByName("item_count");

        goodsBg:loadTexture("images/ui/frame/normal.png");

        if i <= totalGoodsCount then
            grid:setVisible(true);

            local goodsIndex = goodsList[i][1];   -- 商品序号
            local classId    = goodsList[i][2];   -- 商品class_id
            local count      = goodsList[i][3];   -- 商品的数量
            local payAttrib  = goodsList[i][4];   -- 支付属性
            local goodsPrice = goodsList[i][5];   -- 商品价格
            local goodsIcon  = goodsList[i][6];   -- 图标

            -- 为商品图标绑定信息
            iconImg.goodsIndex = goodsIndex;
            iconImg.classId    = classId;
            iconImg.count      = count;
            iconImg.payAttrib  = payAttrib;
            iconImg.goodsPrice = goodsPrice;

            rankNode:setVisible(false);
            countLabel:setVisible(true);
            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
            countLabel:setString(tostring(count));
            countLabel:setPositionX(countLabel:getPositionX() - 3);
            countLabel:setPositionY(countLabel:getPositionY() - 1);

            if count <= 1 then
                countLabel:setVisible(false);
            else
                countLabel:setVisible(true);
            end

            -- 显示商品图标/兑换花费
            local iconPath;
            iconImg:loadTexture(goodsIcon);

            moneyImg:setPositionX(moneyImg:getPositionX() - 40);
            moneyImg:setPositionY(moneyImg:getPositionY() + 10);
            moneyLabel:setPositionX(moneyLabel:getPositionX() - 3);
            moneyLabel:setPositionY(moneyLabel:getPositionY() + 10);

            -- 支付属性（代币）
            local iconPath = getRotineIconPath("token");
            moneyImg:loadTexture(iconPath);
            moneyLabel:setString(tostring(goodsPrice));
            moneyImg:setScale(0.45);

            -- 当前代币数量
            local curScore = self.info["rotine_score"] or 0;

            TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_WHITE, true);
            moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

            if curScore < goodsPrice then
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
            else
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
            end

            local moneyImgW = moneyImg:getContentSize().width;
            moneyImg:setPositionY(moneyImg:getPositionY() - 2 );
            local moneyLabelW = moneyLabel:getContentSize().width;

            moneyLabel:setPositionX(moneyLabel:getPositionX() + 15);
            moneyLabel:setPositionY(moneyLabel:getPositionY() - 1 );

            -- 判断商品已经是否售完
            local soldOut = false;
            if RotineActivityM.isExchangeAlready(goodsIndex) then
                soldOut = true;
                iconImg.soldOut = true;
            end

            if soldOut then
                setGrayTransMode(goodsBg, true);
                setGrayTransMode(iconImg, true);

                -- 不显示价格，星星，数量
                moneyImg:setVisible(false);
                moneyLabel:setVisible(false);
                rankNode:setVisible(false);
                countLabel:setVisible(false);

                -- 已兑换字样
                soldOutLabel:setVisible(true);
                TextStyleM.setTextStyle(soldOutLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
                soldOutLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
                soldOutLabel:setString(getLocStr("has_been_exchange"));
            else
                -- 背景变亮
                setGrayTransMode(goodsBg, false);
                setGrayTransMode(iconImg, false);

                -- 显示图标、价格、星星
                moneyImg:setVisible(true);
                moneyLabel:setVisible(true);
                rankNode:setVisible(true);

                soldOutLabel:setVisible(false);
            end
        else
            -- 清空多余的格子
            grid:setVisible(false);
        end
    end
end

-- 绘制时间
function UIRotineShop:redrawTime()
    -- 提示信息
    local leftTime = ActivityM.getRemainTime(self.id);
    local txt1Label = findChildByName(self.CT, "subhead");

    if self.hasTick then
        TextStyleM.setSubheadStyle(txt1Label);
        txt1Label:setString(remainingTimeDesc2(leftTime));
        return;
    end

    local function tick()
        self.hasTick = true;
        leftTime = ActivityM.getRemainTime(self.id);
        TextStyleM.setSubheadStyle(txt1Label);
        txt1Label:setString(remainingTimeDesc2(leftTime));

        performWithDelay(self, tick, 1);
    end
    tick();
end

-- 获取可购买的商品信息
function UIRotineShop:gatherGoodsInfo()
    local ret = {};
    local bonusInfo = self.info["rotine_bonus"] or {};
    for _, index in pairs(table.keys(bonusInfo)) do
        local info = bonusInfo[index];
        local bonus = info["bonus"][1];
        local price = RotineActivityM.queryBonus(info["id"], "price");
        local cost = price[self.info["rotine_type"]];

        local iconPath = self:getBonusIcon(bonus);
        local item = {index, bonus[2], bonus[3], "rotine_score", cost[2], iconPath};
        table.insert(ret, item);
    end

    return ret;
end

-- 当商品被点击
function UIRotineShop:onGoodsClick(iconImg)
    if iconImg.soldOut then
        alert(getLocStr("goods_exchange_already"));
        return;
    end

    UIMgr.getCurrentScene():removeFormByName("UIRotineShopDetail");
    local uiRotineShopDetail = UIRotineShopDetail.create(iconImg.goodsIndex);
    UIMgr.getCurrentScene():addForm(uiRotineShopDetail);
end

-- 注册商品点击事件
function UIRotineShop:registerPetShopTouchEvent(node)
    -- 注册商品图标点击事件
    local image = node:getChildByName("bg");
    local iconImg = node:getChildByName("goods_icon");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            image:runAction(cc.ScaleTo:create(0.1, 0.90));
        elseif eventType == ccui.TouchEventType.canceled then
            image:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_spell");
            image:runAction(cc.ScaleTo:create(0.1, 1));
            self:onGoodsClick(iconImg);
        end
    end
    image:addTouchEventListener(onClick)
end

-- 注册事件处理回调函数
function UIRotineShop:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIRotineShop", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIRotineShop" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_ROTINE_ACTIVITY);
        end
    end);

    -- 关注购买商品的事件
    EventMgr.register("UIRotineShop", event.ROTINE_EXCHANGE_RESULT, function(args)
        local index = args.index;
        local result = args.result;

        -- 更新一下信息
        self.info = RotineActivityM.getUserRotineInfo();

        if result == 1 then
            self:whenBuyGoods(index);
        else
            alert(getLocStr("rotine_score_fail_tip"));
        end
    end);

    -- 注册玩家信息更新的回调
    EventMgr.register("UIRotineShop", event.USER_INFO_UPDATED, function(args)
        -- 常规活动
        if args == "rotine_activity_info" then
            -- 更新信息
            self.info = RotineActivityM.getUserRotineInfo();
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIRotineShop 界面析构清理");
            EventMgr.removeAll("UIRotineShop");
        elseif eventType == "enter" then
        end
    end);
end

-- 注册点击事件
function UIRotineShop:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIRotineShop");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 关闭购买商品的消息
function UIRotineShop:whenBuyGoods(index)
    -- 刷新界面
    self:redraw();

    if not index then
        return;
    end

    -- 提示玩家购买了商品
    local function delay()
        local bonus = RotineActivityM.getTreasureBonus(index);
        local count = bonus[3];
        local name;
        if bonus[1] == 1 then
            name = ItemM.query(bonus[2], "name");
        elseif bonus[1] == 2 then
            name = FieldsM.query(bonus[2], "name");
        end
        alert(string.format(getLocStr("exchange_scraps_done"), name, count));
    end

    performWithDelay(self, delay, 0.1);
end